# -*- coding: utf-8 -*-
# Create time: 2020-03-12 16:12
# Author:Rongzhikai
from conf.settings import PROJECT_IP
import jsonpath
import json
import time
from libs.logger import myLogger


class GlobalVariables(object):
    __gv = None

    # 单例模式创建实例
    def __new__(cls, *args, **kwargs):
        if cls.__gv is None:
            cls.__gv = object.__new__(cls)
            return cls.__gv
        else:
            return cls.__gv

    def __init__(self):
        self.globalVars = {"ip": PROJECT_IP, "ntime": 'nowtime'}
        self.res = []
        # 计数成功和失败的次数
        self.pass_count = 0
        self.fail_count = 0

    def setVar(self, key, value):
        """添加全局变量"""
        self.globalVars[key] = value
        myLogger.debug(u'>>>当前全局变量：%s' % self.globalVars)
        # print("当前全局变量：", self.globalVars)

    def getVar(self, key):
        """获取某个全局变量"""
        self.setVar('ntime', time.strftime('%Y%m%d%H%M%S'))  # 每次获取前生成一个当前时间，便于造数据时不一样区别
        return self.globalVars.get(key, '')

    def getVars(self):
        """获取全部全局变量"""
        return self.globalVars

    def deleteVar(self, key):
        """删除某个全局变量"""
        self.globalVars.pop(key)

    def cleanVars(self):
        """清空全局变量"""
        self.globalVars.clear()

    def deleteVars(self):
        """删除全局变量"""
        del self.globalVars

    # 处理被保存全局变量，待利用
    def save_globalvariable(self, globalVariable, res):
        if globalVariable is None:
            return
        lists_globalvar = globalVariable.split(';')  # 分割多个需保存的变量
        for gvar in lists_globalvar:  # 逐个对全局变量拿出来处理
            gvar = gvar.strip()
            if gvar:
                key_temp = gvar[:gvar.find('=')]  # 待添加key到全局变量，切片操作
                value_temp = gvar[gvar.find('=')+1:]  # 切片获取准确的Jsonpath，以免有==字符干扰
                try:
                    value_temp = jsonpath.jsonpath(json.loads(res), value_temp)[0]  # 待添加value到全局变量
                except Exception as e:
                    myLogger.debug(u'------寻址异常，关联的是普通字符串')
                self.setVar(key_temp, value_temp)  # 添加全局变量


# 获得单个对象
gvar = GlobalVariables()

# if __name__ == '__main__':
#     gv = GlobalVariables()
#     f = open('../data/datas.json')
#     data = json.load(f, encoding='utf-8')
#     f.close()
#     data = json.dumps(data, ensure_ascii=False)
#     globalVariable = 'a=$.adduser;'
#     gv.save_globalvariable(globalVariable, data)
